const azdev = require('azure-devops-node-api');

const token = process.env.TOKEN;
if (!token) {
    throw new Exception('No token provided');
}

const releaseBranch = process.argv[2];
if (!releaseBranch) {
    throw new Exception('No release branch provided');
}

const orgUrl = 'https://dev.azure.com/mseng';
const authHandler = azdev.getPersonalAccessTokenHandler(token);

const azureDevOpsRepoId = 'fb240610-b309-4925-8502-65ff76312c40';
const project = 'AzureDevOps';

const refs = {
    sourceRefName: `refs/heads/${releaseBranch}`,
    targetRefName: 'refs/heads/master'
};

const pullRequestToCreate = {
    ...refs,
    title: 'Courtesy Bump of Tasks',
    description: 'Autogenerated PR to bump the versions of our first party tasks'
};

const createPullRequest = async () => {
    console.log('Getting connection');
    const connection = new azdev.WebApi(orgUrl, authHandler);
    console.log('Getting Git API');
    const gitApi = await connection.getGitApi();
    console.log('Checking if an active pull request for the source and target branch already exists');
    let PR = (await gitApi.getPullRequests(azureDevOpsRepoId, refs, project))[0];

    if (PR) {
        console.log('PR already exists');
    } else {
        console.log('PR does not exist; creating PR');
        PR = await gitApi.createPullRequest(pullRequestToCreate, azureDevOpsRepoId, project);
    }

    const prLink = `${orgUrl}/${project}/_git/${project}/pullrequest/${PR.pullRequestId}`;
    console.log(`Link to the PR: ${prLink}`);
    console.log(`##vso[task.setvariable variable=PR_ID]${PR.pullRequestId}`);
    console.log(`##vso[task.setvariable variable=PR_LINK]${prLink}`);
};

try {
    createPullRequest();
} catch (err) {
    console.log(err);
    throw err;
}
